<template>
  <div class="container">
    <div id="container-map" v-show="mapDisplay"></div>
    <SpringView ref="test"></SpringView>
    <CaseDetails ref="case"></CaseDetails>
    <LaojiuxiaoquPopup ref="laojiu"></LaojiuxiaoquPopup>
    <MenTouBaoShen ref="mentou"></MenTouBaoShen>
    <BujianMapPopup ref="bujianmap"></BujianMapPopup>
    <section class="icon-shili" v-if="pointType == 1">
      <div style="color: #fff; font-weight: bold; font-size: 16px">空气质量指数</div>
      <p :key="'a' + index" v-for="(item, index) in colorList">
        <span :style="{ background: item.background }"></span>
        <span>{{ item.value }}</span>
      </p>
    </section>

    <section
      :class="homeDianwei ? 'home-dianewi' : ''"
      :style="`bottom:${bottom}px`"
      class="icon-laojiu icon-shili"
      v-if="pointType == 3 || homeDianwei">
      <p :key="'a' + index" v-for="(item, index) in laojiuList">
        <img :src="item.img" alt />
        <span>{{ item.num }}</span>
      </p>
    </section>
    <section class="container-box">
      <ScreenNav :navType="navType"></ScreenNav>
      <div class="router-view">
        <RouterView v-if="isrouterDisplay" />
      </div>
    </section>
  </div>
</template>

<script>
const baseUrl = process.env.VUE_APP_BASE_URL
import ScreenNav from '@/components/ScreenNav/ScreenNav.vue' //顶部导航
import SpringView from '@/components/springView.vue'
// import SpringView from "@/components/springView.vue";
// import SpringView from "@/components/monitoringPopup.vue"
import CaseDetails from '@/components/caseDetails.vue'
import LaojiuxiaoquPopup from '@/components/laojiuxiaoquPopup.vue'
import MenTouBaoShen from '@/components/MenTouBaoShen.vue'
import BujianMapPopup from '@/components/bujianDetail.vue'
import { VideoListDB } from '@/api'

import {
  YangChenJianCeDB,
  getViDeviceList,
  ZhiHuiGongDiDB,
  ZhanDaoJingYing,
  LaoJiuXiaoQuDB,
  MenTouBaoShenDB,
  HomeDb,
  queryBuJianPointList,
  queryBuJianAreaList,
  YingPanShiDian,
  BuJianMapDB,
  ShiChangJianDuDB,
  MarketSurveillanceDB,
  JieXiangChuiShaoDB
} from '@/api'
import Bus from '@/untils/bus'
import https from '@request/https'
// 地图相关参数
let MapContainer = null
let AMap_Center = ['112.88', '36.12']
let AMap_MarkerList = []
let AMap_HomeMarkerList = []
let AMap_Layer = null
let AMap_LabelMarker = []
let heatmap = null
let BUJIANLIST = []
let polygons = []
let clusterss = null
let AMap_HeatMap = null
let POLYGON_LIST = []

export default {
  components: {
    SpringView,
    ScreenNav,
    CaseDetails,
    LaojiuxiaoquPopup,
    MenTouBaoShen,
    BujianMapPopup
  },
  data() {
    return {
      weilanList: [],
      markers: [],
      temporaryList1: [],
      infoWindow: null,
      jynPlayer0: null,
      monitorData: {},
      siteNum: 0,
      PointType: 1,
      pageType: 1,
      mapDisplay: true,
      loca: null,
      colorList: [
        {
          background: '#39F707',
          // value: '0 ~ 50',
          value: '优'
        },
        {
          background: '#DBC900',
          // value: '51 ~ 100',
          value: '良'
        },
        {
          background: '#FD6601',
          // value: '101 ~ 150',
          value: '轻度污染'
        },
        {
          background: '#FC0102',
          // value: '151 ~ 200',
          value: '中度污染'
        },
        {
          background: '#910294',
          // value: '201 ~ 300',
          value: '重度污染'
        },
        {
          background: '#4e0300',
          // value: '>300',
          value: '严重污染'
        }
      ],
      pointType: null,
      laojiuList: [],
      time1: null,
      homeDianwei: false,
      isrouterDisplay: true,
      bjMapAreaArr: [],
      PI: 3.14159265358979324,
      Index: 0, //显示地图的index
      positionList: [], //接口请求的数据
      centralPoint: [112.580406, 37.826344],
      gridPolygons: [],
      dataMsg: {},
      timer: null,
      centerMapCore: [],
      markers: [], //数组
      bottom: 0,
      monitoringType: 0,
      streetId: '',
      bujianName: null,
      isOrder: 0,
      navType: ''
    }
  },
  mounted() {
    this.initMap()
  },

  beforeDestroy() {
    clearInterval(this.time1)
  },

  watch: {
    $route: {
      handler: function (route, oderValue) {
        if (oderValue && oderValue.fullPath == '/jklb') {
          location.reload()
        }
        // 清除点位
        this.reload()
        if (AMap_MarkerList.length) {
          MapContainer.remove(AMap_MarkerList)
        }

        if (AMap_LabelMarker.length) {
          AMap_Layer.remove(AMap_LabelMarker)
          MapContainer.remove(AMap_Layer)
        }

        AMap_MarkerList = []
        AMap_LabelMarker = []
        AMap_HomeMarkerList = []
        MapContainer = null

        if (route.fullPath.includes('jklb')) {
          this.mapDisplay = false
          this.navType = ''
        } else if (route.fullPath.includes('scjd')) {
          this.navType = 'scjd'
        } else if (route.fullPath.includes('jxcs')) {
          this.navType = 'jxcs'
        } else {
          this.navType = ''
          this.mapDisplay = true
        }
        this.$nextTick(() => {
          this.pointType = null
          this.homeDianwei = false
          this.Index = 0
          this.initMap()
          clearInterval(this.time1)

          if (route.fullPath.includes('ycjc')) {
            this.monitoringType = 0
            this.getYangChenPoints()
            this.pointType = 1
          }

          if (route.fullPath.includes('zhgd')) {
            // this.homeDianwei = true
            this.getNewOrder()
          }

          if (route.fullPath.includes('zdjj')) {
            // this.homeDianwei = true
            this.getNewList()
          }

          if (route.fullPath.includes('ljxq')) {
            this.bottom = 100
            this.pointType = 3
            this.getCommunityList()
          }

          if (route.fullPath.includes('mtbs')) {
            this.bottom = 360
            this.getGpsList()
          }

          if (route.fullPath.includes('zhjx')) {
            this.bottom = 360
            this.homeDianwei = false
            this.Index = 1
            this.ZhiHuiJieXiang('1298860969509908481')
            this.getYpsdList()
          }

          if (route.fullPath.includes('default')) {
            this.bottom = 420
            this.homeDianwei = true
            // this.homeZuiXinAnJian()
          }

          if (route.fullPath.includes('scjd')) {
            this.bottom = 360
            this.homeDianwei = false
            this.Index = 1
            // this.ZhiHuiJieXiang("1298860772859965441",'scjd');
            this.heatmapAmap()
            this.shiChangJianDuFn()
            this.getYpsdList('坞城街道')
          }

          if (route.fullPath.includes('jxcs')) {
            this.monitoringType = 0
            this.bottom = 360
            this.pointType = null
            this.streetId = '0'
            this.getChuiShaoPoints('streetId', '0')
            this.getYpsdList()
          }
        })
      },
      immediate: true
    }
  },

  methods: {
    // 84转火星
    getMars(item) {
      //网格范围信息
      var geometry = JSON.parse(item)
      var coordinates = geometry
      var newCoordinates = []
      //坐标转换 wgs84转gcj02
      for (var j = 0; j < coordinates[0].length; j++) {
        var latlngTmp = coordinates[0][j]
        if (latlngTmp.length <= 2) {
          newCoordinates.push(this.gcj_encrypt_new(latlngTmp[1], latlngTmp[0]))
        } else {
          var tmpNew = latlngTmp
          var tmpNew2 = []
          // $.each(tmpNew,function(h){
          //   var tmpNewItem = tmpNew[h];
          //   tmpNew2.push(this.gcj_encrypt_new(tmpNewItem[1],tmpNewItem[0]));
          // });
          for (var h = 0; h < tmpNew.length; h++) {
            var tmpNewItem = tmpNew[h]
            tmpNew2.push(this.gcj_encrypt_new(tmpNewItem[1], tmpNewItem[0]))
          }
          newCoordinates.push(tmpNew2)
        }
      }
      return newCoordinates
    },
    //
    gcj_encrypt_new(wgsLat, wgsLon) {
      if (this.outOfChina(wgsLat, wgsLon)) return [wgsLon, wgsLat]
      var d = this.delta(wgsLat, wgsLon)
      return [wgsLon + d.lon, wgsLat + d.lat]
    },
    outOfChina(lat, lon) {
      if (lon < 72.004 || lon > 137.8347) return true
      if (lat < 0.8293 || lat > 55.8271) return true
      return false
    },
    delta(lat, lon) {
      var a = 6378245.0 //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
      var ee = 0.00669342162296594323 //  ee: 椭球的偏心率。
      var dLat = this.transformLat(lon - 105.0, lat - 35.0)
      var dLon = this.transformLon(lon - 105.0, lat - 35.0)
      var radLat = (lat / 180.0) * this.PI
      var magic = Math.sin(radLat)
      magic = 1 - ee * magic * magic
      var sqrtMagic = Math.sqrt(magic)
      dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * this.PI)
      dLon = (dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * this.PI)
      return { lat: dLat, lon: dLon }
    },
    transformLat(x, y) {
      var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x))
      ret += ((20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0) / 3.0
      ret += ((20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin((y / 3.0) * this.PI)) * 2.0) / 3.0
      ret += ((160.0 * Math.sin((y / 12.0) * this.PI) + 320 * Math.sin((y * this.PI) / 30.0)) * 2.0) / 3.0
      return ret
    },
    transformLon(x, y) {
      var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x))
      ret += ((20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0) / 3.0
      ret += ((20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin((x / 3.0) * this.PI)) * 2.0) / 3.0
      ret += ((150.0 * Math.sin((x / 12.0) * this.PI) + 300.0 * Math.sin((x / 30.0) * this.PI)) * 2.0) / 3.0
      return ret
    },
    //获取多边形中心点
    getTheAreaCenter(lnglatarr) {
      var total = lnglatarr.length
      var X = 0,
        Y = 0,
        Z = 0
      for (var i = 0; i < lnglatarr.length; i++) {
        var lng = (lnglatarr[i].lng * Math.PI) / 180
        var lat = (lnglatarr[i].lat * Math.PI) / 180
        var x, y, z
        x = Math.cos(lat) * Math.cos(lng)
        y = Math.cos(lat) * Math.sin(lng)
        z = Math.sin(lat)
        X += x
        Y += y
        Z += z
      }
      X = X / total
      Y = Y / total
      Z = Z / total
      var Lng = Math.atan2(Y, X)
      var Hyp = Math.sqrt(X * X + Y * Y)
      var Lat = Math.atan2(Z, Hyp)
      return [(Lng * 180) / Math.PI, (Lat * 180) / Math.PI]
    },
    // 初始化地图
    initMap() {
      MapContainer = new AMap.Map('container-map', {
        mapStyle: 'amap://styles/8f96cd8332c1178d0ae03e5a8f81a423',
        viewMode: '2D',
        zoom: 10,
        rotation: 0,
        center: AMap_Center,
        zooms: [2, 20]
      })
      this.weilanListFn()
    },

    /**
     * 电子网格数据
     */
    weilanListFn() {
      MapContainer.remove(POLYGON_LIST);
        POLYGON_LIST = []
        const params = {}
        this.weilanList = []
        VideoListDB.gridListDB(params).then(res => {
            res.data.forEach((item, index) => {
                let pathData = JSON.parse(item.coordinates)
                let polygon = new AMap.Polygon({ path: pathData })
                this.weilanList.push({
                    ...item,
                    path: polygon
                })
                polygon.setExtData(item)
                polygon.on('click', (e) => {
                    let data = e.target.getExtData();
                    // polygonClick(item, index)
                })
                POLYGON_LIST.push(polygon)
            })

            MapContainer.add(POLYGON_LIST);
            MapContainer.setFitView();
        })
    },

//     polygonClick(data, index){
//     if (this.weilanEdit) {
//         this.selected = index
//         if (data.streetId) {
//             streetValue.value = [streetlist.value[0].id, data.streetId, data.communityId]
//             selectedData.value = [streetlist.value[0].title, data.street, data.community]
//         }
//         POLY_EDITOR.setTarget(POLYGON_LIST[index]);
//         POLYGON = POLYGON_LIST[index]
//         POLY_EDITOR.open();
//     } else {
//         gridDataRef.value.gridDataModalFn(data)
//     }
// }

    heatmaps(positionList) {
      AMap.plugin('AMap.DistrictSearch', () => {
        // 创建行政区查询对象
        var district = new AMap.DistrictSearch({
          // 返回行政区边界坐标等具体信息
          extensions: 'all',
          // 设置查询行政区级别为 区
          level: 'district'
        })

        district.search('小店区', (status, result) => {
          var bounds = null
          let path = []
          this.removeLine(polygons)
          polygons = []
          if (this.Index == 1) {
            this.laojiuList = [
              {
                img: require('@assets/images/zaixian.png'),
                num: '在线网格员'
              },
              {
                img: require('@assets/images/lixian.png'),
                num: '离线网格员'
              }
            ]
            if (!positionList && positionList == undefined) {
              return false
            }
            bounds = positionList
          } else {
            bounds = result.districtList[0].boundaries
            // 赋值之后异步重新设置地图中心点位置和缩放
            setTimeout(() => {
              MapContainer.setCenter(AMap_Center)
              MapContainer.setZoom(12)
            }, 0)
          }
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              if (this.Index == 1) {
                if (bounds[i].coordinates != '') {
                  path = this.getMars(bounds[i].coordinates)
                }
              }
              var polygon = new AMap.Polygon({
                map: MapContainer,
                strokeWeight: 1,
                path: this.Index == 1 ? path : bounds[i],
                strokeColor: '#49D0EC',
                strokeWeight: 4,
                strokeOpacity: 0.5,
                fillColor: '#000',
                fillOpacity: 0,
                strokeStyle: 'solid',
                strokeDasharray: [10, 2, 10]
              })
              if (this.Index == 1) {
                polygons.push(polygon)
              } else {
                BUJIANLIST.push(polygon)
              }
              if (this.navType !== 'scjd') {
                MapContainer.setFitView()
              }
            }
          }
        })
      })
    },

    // //销毁边线
    removeLine(arr) {
      MapContainer.remove(arr)
    },

    // 首页点位加载
    homeZuiXinAnJian() {
      HomeDb.getHomeDianwei().then((res) => {
        let list = []
        res.data.forEach((item) => {
          if (item.lon && item.lat) {
            list.push({
              lon: item.lon,
              lat: item.lat,
              id: item.id,
              state: item.state,
              orderNum: item.orderNum
            })
          }
        })
        this.laojiuList = [
          {
            img: require('@assets/images/home/chuli1.jpg'),
            num: '待处理'
          },
          {
            img: require('@assets/images/home/chili2.jpg'),
            num: '处理中'
          },
          {
            img: require('@assets/images/home/chuli3.jpg'),
            num: '已超期'
          }
        ]
        this.listMarkerCluster(list, 5)
        // this.getHomeMapList();
      })
    },

    //智慧街乡点位地图
    ZhiHuiJieXiang(data, _type) {
      HomeDb.getHomeDianwei({ departmentId: data }).then((res) => {
        let list = []
        res.data.forEach((item) => {
          if (item.lon && item.lat) {
            list.push({
              lon: item.lon,
              lat: item.lat,
              id: item.id,
              state: item.state,
              orderNum: item.orderNum
            })
          }
        })
        //点位渲染
        if (_type == 'scjd') {
          this.renderMapPoint(list, 12)
        } else {
          this.renderMapPoint(list, 11)
        }
      })
    },

    // 网格地图获取
    getYpsdList(data) {
      const params = {
        street: data || '北营街道'
      }

      YingPanShiDian.gridDataSelectByStreet(params).then((res) => {
        // this.centerMapCore = [res.data.core.lon, res.data.core.lat];
        this.heatmaps(res.data.data)
      })
    },

    // 部件地图点位
    bujianMapMaker() {
      const params = {
        name: this.bujianName,
        isOrder: this.isOrder
      }
      BuJianMapDB.baseGetGps(params).then((res) => {
        let list = []
        res.data.forEach((item) => {
          if (item.state == 4) {
            return
          }
          if (item.x2000 && item.y2000) {
            list.push({
              lon: item.x2000,
              lat: item.y2000,
              img: item.picture,
              id: item.id
            })
          }
        })
        this.$nextTick(() => {
          this.listMarkerCluster(list, 12)
        })
      })
    },

    // 修改地图点位
    getUpdateOrderState() {
      HomeDb.getUpdateOrderState().then((res) => {
        if (res.data.length < 1) {
          return
        }
        res.data.forEach((item, index) => {
          AMap_HomeMarkerList.forEach((items, indexs) => {
            if (items.id == item.id) {
              if (item.state != 4) {
                items.state = item.state
              } else {
                AMap_HomeMarkerList.splice(indexs, 1)
              }
            }
          })
        })
        if (res.data.length > 0) {
          AMap_Layer.remove(AMap_LabelMarker)
          MapContainer.remove(AMap_Layer)
          this.$nextTick(() => {
            this.listMarkerCluster(AMap_HomeMarkerList, 6)
          })
        }
      })
    },

    // 加载扬尘点位信息
    getYangChenPoints() {
      const params = {
        type: this.monitoringType
      }
      YangChenJianCeDB.dianweiList(params).then((res) => {
        if (res.code == 200) {
          let list = []
          res.data.forEach((element) => {
            list.push({
              lon: element.longitude,
              lat: element.latitude,
              aqi: element.aqi,
              number: element.site_number,
              title: element.site_name,
              count: element.aqi
            })
          })
          this.renderMapPoint(list, 1)
        }
      })
    },

    //占道经营点位信息
    getNewList() {
      ZhanDaoJingYing.GetNewList().then((res) => {
        let list = []
        res.data.forEach((element) => {
          if (element.lat && element.lon) {
            list.push({
              lon: element.lon,
              lat: element.lat,
              id: element.id,
              staFrom: element.staFrom,
              orderNum: element.orderNum
            })
          }
        })
        this.laojiuList = [
          {
            img: require('@assets/images/home/chuli1.jpg'),
            num: '待处理'
          },
          {
            img: require('@assets/images/home/chili2.jpg'),
            num: '处理中'
          },
          {
            img: require('@assets/images/home/chuli3.jpg'),
            num: '已超期'
          }
        ]
        this.renderMapPoint(list, 4)
      })
    },

    // 智慧工地点位信息
    getNewOrder() {
      ZhiHuiGongDiDB.getNewOrder().then((res) => {
        let list = []
        res.data.forEach((element) => {
          if (element.lat && element.lon) {
            list.push({
              lon: element.lon,
              lat: element.lat,
              id: element.id,
              staFrom: element.staFrom,
              orderNum: element.orderNum
            })
          }
        })
        this.laojiuList = [
          {
            img: require('@assets/images/home/chuli1.jpg'),
            num: '待处理'
          },
          {
            img: require('@assets/images/home/chili2.jpg'),
            num: '处理中'
          },
          {
            img: require('@assets/images/home/chuli3.jpg'),
            num: '已超期'
          }
        ]
        this.renderMapPoint(list, 4)
      })
    },

    // 老旧小区列表
    getCommunityList() {
      LaoJiuXiaoQuDB.getCommunityList().then((res) => {
        let list = []
        res.data.forEach((element) => {
          if (element.lat && element.lon) {
            list.push({
              lon: element.lon,
              lat: element.lat,
              id: element.id,
              total: element.total
              // staFrom: element.staFrom,
            })
          }
        })
        this.laojiuList = [
          {
            img: require('@assets/images/laojiuxiaoqu/lv.png'),
            num: '案件数量：0-10'
          },
          {
            img: require('@assets/images/laojiuxiaoqu/cheng.png'),
            num: '案件数量：11-20'
          },
          {
            img: require('@assets/images/laojiuxiaoqu/hong.png'),
            num: '案件数量：>20'
          }
        ]
        this.listMarkerCluster(list, 3)
      })
    },

    // 门头报审
    getGpsList() {
      MenTouBaoShenDB.getGpsList().then((res) => {
        let list = []
        res.data.forEach((element) => {
          if (element.beforCheck == 2) {
            return
          }
          if (element.currLat && element.currLng) {
            list.push({
              lon: element.currLng,
              lat: element.currLat,
              id: element.id,
              beforCheck: element.beforCheck
            })
          }
        })
        this.pointType = 3
        this.laojiuList = [
          {
            img: require('@assets/images/mentoubaoshen/daishenhe.png'),
            num: '待审核'
          },
          {
            img: require('@assets/images/mentoubaoshen/tongguo.png'),
            num: '已通过'
          }
        ]
        this.listMarkerCluster(list, 1)
      })
    },

    //街乡吹哨
    getChuiShaoPoints(type, data) {
      const params = {
        streetId: type === 'streetId' ? data : this.streetId,
        type: type === 'type' ? data : '1'
      }
      JieXiangChuiShaoDB.getOaStreetWhistleOrdertGpsStreetOrder(params).then((res) => {
        if (res.code == 200) {
          let list = []
          res.data.forEach((element) => {
            if(element.longitude && element.latitude) {
              list.push({
                lon: element.longitude,
                lat: element.latitude,
                id: element.id,
                orderNum: element.orderNum,
                orderId: element.orderId
              })
            }
          })
          this.renderMapPoint(list, 16)
        }
      })
    },

    // 市场监督
    shiChangJianDuFn() {
      const params = {
        orgId: '1298860772859965441'
      }
      ShiChangJianDuDB.getKeyAreas(params).then((res) => {
        console.log(res, 'getKeyAreas')
        let list = []
        res.data.forEach((item) => {
          list.push({
            lon: item.lon,
            lat: item.lat,
            icon: item.icon
          })
        })
        this.renderMapPoint(list, 15)
      })
    },
    // 海量点位
    listMarkerCluster(list, type) {
      if (type == 5) {
        AMap_HomeMarkerList = [...AMap_HomeMarkerList, ...list]
      }
      let openType = 'ment'
      AMap_Layer = new AMap.LabelsLayer({
        zooms: [2, 20],
        zIndex: 10000,
        collision: false
      })
      // 图标
      list.forEach((item) => {
        let icon = {
          image: null,
          type: 'image',
          size: [34, 42],
          anchor: 'bottom-center'
        }
        if (type == 1) {
          if (item.beforCheck === 1) {
            icon = {
              image: require('@assets/images/mentoubaoshen/tongguo.png'),
              type: 'image',
              size: [34, 42],
              anchor: 'bottom-center'
            }
          }
          if (item.beforCheck === 0) {
            icon = {
              image: require('@assets/images/mentoubaoshen/daishenhe.png'),
              type: 'image',
              size: [34, 42],
              anchor: 'bottom-center'
            }
          }
        }

        // 老旧小区点位
        if (type == 3) {
          openType = 'laojiu'
          // IconSrc = require('@assets/images/laojiuxiaoqu/lv.png');
          if (item.total < 11) {
            icon = {
              image: require('@assets/images/laojiuxiaoqu/lv.png'),
              type: 'image',
              size: [34, 42],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/laojiuxiaoqu/lv.png');
          } else if (item.total > 11 && item.total < 20) {
            icon = {
              image: require('@assets/images/laojiuxiaoqu/cheng.png'),
              type: 'image',
              size: [34, 42],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/laojiuxiaoqu/cheng.png')
          } else if (item.total > 20) {
            icon = {
              image: require('@assets/images/laojiuxiaoqu/hong.png'),
              type: 'image',
              size: [34, 42],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/laojiuxiaoqu/hong.png')
          }
        }

        // 首页点位添加
        if (type == 5 || type == 6) {
          openType = 'case'
          icon.size = [50, 50]
          if (item.state == 1) {
            icon = {
              image: require('@assets/images/home/chuli1.jpg'),
              type: 'image',
              size: [50, 50],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/home/chuli1.jpg')
          } else if (item.state == 2) {
            icon = {
              image: require('@assets/images/home/chili2.jpg'),
              type: 'image',
              size: [50, 50],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/home/chili2.jpg')
          } else if (item.state == 3) {
            icon = {
              image: require('@assets/images/home/chuli3.jpg'),
              type: 'image',
              size: [50, 50],
              anchor: 'bottom-center'
            }
            // icon.image = require('@assets/images/home/chuli3.jpg')
          }
        }

        if (type == 12) {
          openType = 'bujianmap'
          icon = {
            image: require('@assets/images/bujianMap/kj.png'),
            type: 'image',
            size: [50, 50],
            anchor: 'bottom-center'
          }
        }
        //  this.$nextTick(() => {
        var curData = {}
        if (type == 4) {
          curData = {
            position: [item.lon, item.lat]
          }
        } else {
          curData = {
            position: [item.lon, item.lat],
            icon
          }
        }
        var labelMarker = new AMap.LabelMarker(curData)
        labelMarker.setExtData(item)
        labelMarker.on('click', (e) => {
          let el = e.target.getExtData()
          this.pointPopup(el, openType)
        })
        AMap_LabelMarker.push(labelMarker)
        icon = null
      })
      AMap_Layer.add(AMap_LabelMarker)
      MapContainer.add(AMap_Layer)
    },

    //点位渲染
    renderMapPoint(list, types) {
      this.pointType = types
      let IconSrc = ''
      let Size1 = 34
      let Size2 = 42
      let type = 'text'

      // 循环生成marker
      list.forEach((item) => {
        if (types == 1) {
          if (Number(item.aqi) < 50) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng1.png')
          } else if (Number(item.aqi) > 50 && Number(item.aqi) < 100) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng2.png')
          } else if (Number(item.aqi) > 100 && Number(item.aqi) < 150) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng3.png')
          } else if (Number(item.aqi) > 150 && Number(item.aqi) < 200) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng4.png')
          } else if (Number(item.aqi) > 200 && Number(item.aqi) < 300) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng5.png')
          } else if (Number(item.aqi) > 300) {
            IconSrc = require('@assets/images/yangchenjiance/yangcheng6.png')
          }
        }

        if (item.staFrom && types == 2) {
          Size1 = 130
          Size2 = 142
          type = 'case'

          if (item.staFrom == '1') {
            IconSrc = require('@assets/images/zhandao.gif')
          } else if (item.staFrom == '2') {
            IconSrc = require('@assets/images/zhandao.gif')
          }
        }

        if (types == 3) {
          type = 'laojiu'
          IconSrc = require('@assets/images/laojiuxiaoqu/lv.png')
          if (item.total < 11) {
            IconSrc = require('@assets/images/laojiuxiaoqu/lv.png')
          } else if (item.total > 11 && item.total < 20) {
            IconSrc = require('@assets/images/laojiuxiaoqu/cheng.png')
          } else if (item.total > 20) {
            IconSrc = require('@assets/images/laojiuxiaoqu/hong.png')
          }
        }

        if (types == 4) {
          type = 'case'
          IconSrc = require('@assets/images/home/chili2.jpg')
          Size1 = Size2 = 34
        }

        if (types == 11) {
          type = 'case'
          Size1 = Size2 = 40
          IconSrc = require('@assets/images/home/chuli1.jpg')
          if (item.state == 1) {
            IconSrc = require('@assets/images/home/chuli1.jpg')
          } else if (item.state == 2) {
            IconSrc = require('@assets/images/home/chili2.jpg')
          } else if (item.state == 3) {
            IconSrc = require('@assets/images/home/chuli3.jpg')
          }
        }

        if (types == 12) {
          type = 'case'
          Size1 = 33
          Size2 = 22
          IconSrc = require('@assets/images/shichangjiandu/chuli1.png')
          if (item.state == 1) {
            IconSrc = require('@assets/images/shichangjiandu/chuli2.png')
          } else if (item.state == 2) {
            IconSrc = require('@assets/images/shichangjiandu/chuli3.png')
          }
        }

        if (types == 16) {
          type = 'case'
          Size1 = 64
          Size2 = 64
          IconSrc = require('@assets/images/jiexiangchuishao/map-icon.png')
        }

        if (types == 15) {
          type = null
          Size1 = 24
          Size2 = 24
          IconSrc = item.icon
        }
        let obj = {
          position: new AMap.LngLat(item.lon, item.lat),
          offset: new AMap.Pixel(-15, -15),
          zIndex: 100,
          data: item,
          icon: new AMap.Icon({
            image: IconSrc,
            imageSize: new AMap.Size(Size1, Size2)
          })
        }
        var marker = new AMap.Marker(obj)
        marker.setExtData(item)
        marker.on('click', (e) => {
          let el = e.target.getExtData()
          this.pointPopup(el, type)
        })
        AMap_MarkerList.push(marker)
      })
      MapContainer.add(AMap_MarkerList)
    },

    // 聚合点位
    aggregationPoint(list) {
      var styles = require('../assets/images/close.png')
      let points = []
      var _renderClusterMarker = function (context) {
        var div = document.createElement('img')
        div.style.width = '30px'
        div.style.height = '30px'
        div.src = styles
        context.marker.setContent(div)
      }
      var _renderMarker = function (context) {
        var content = `<img src="${styles}" alt="" id="dianweiImg" style="width: 30px; height: 30px">`
        var offset = new AMap.Pixel(-16, -30)
        context.marker.setContent(content)
        context.marker.setOffset(offset)
        // context.marker.setExtData({
        //   id: 20
        // });
        // context.marker.on('click', ev => {
        //     const extData = ev.target.getExtData()
        //   });
      }
      let data = []
      list.forEach((item) => {
        if (item.lon && item.lat) {
          points.push({
            lnglat: [item.lon, item.lat],
            id: item.id
          })
          // data.push(item.id);
        }
      })
      MapContainer.add(points)
      MapContainer.plugin(['AMap.MarkerClusterer'], () => {
        clusterss = new AMap.MarkerClusterer(
          MapContainer, // 地图实例
          points, // 海量点数据，数据中需包含经纬度信息字段 lnglat
          {
            gridSize: 100, // 聚合网格像素大小
            renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
            renderMarker: _renderMarker // 自定义非聚合点样式
          },
          data
        )
      })
    },

    // 部件地图 -- 获取点位
    getBjMapPoint(data) {
      queryBuJianPointList({
        typeSubId: data.typeSubId
      }).then((res = []) => {
        let list = []
        // todo 太卡
        // for(let i = 0; i < res.length; i++) {
        for (let i = 0; i < 400; i++) {
          let item = res[i]
          let coordinates
          try {
            coordinates = JSON.parse(item.coordinates)
          } catch (e) {
            continue
          }
          let lon = coordinates[0]
          let lat = coordinates[1]
          list.push({
            lon,
            lat,
            id: item.id,

            staFrom: item.staFrom,
            orderNum: item.orderNum,
            ...item
          })
        }
        if (AMap_MarkerList.length) {
          MapContainer.remove(AMap_MarkerList)
          AMap_MarkerList = []
        }
        // this.aggregationPoint(list);
        this.renderMapPoint(list, 5)
      })
    },

    // 部件地图 -- 获取区域
    getBjMapArea(data) {
      queryBuJianAreaList({
        title: data.community
      }).then((res) => {
        this.Index = 1
        this.heatmaps(res)
      })
    },

    // 热力图
    heatmapAmap() {
      MarketSurveillanceDB.getCommunityOrderNum({
        orgId: '1301571732182839297'
      }).then((res) => {
        let heatmapData = []
        res.data.forEach((item) => {
          heatmapData.push({
            lat: item.lat,
            lng: item.lon,
            count: item.num
          })
        })
        console.log(heatmapData, 'heatmapData')
        MapContainer.plugin(['AMap.HeatMap'], function () {
          //初始化heatmap对象
          AMap_HeatMap = new AMap.HeatMap(MapContainer, {
            radius: 80, //给定半径
            opacity: [0, 0.8]

            // gradient:{
            //   0.1: 'blue',
            //   0.2: 'rgb(117,211,180)',
            //   0.3: 'rgb(117,211, 0)',
            //   0.4:'rgb(0, 255, 255)',
            //   0.5:'rgb(0, 255, 20)',
            //   0.6: 'rgb(117,211,248)',
            //   0.7: 'rgb(0,211,248)',
            //   0.8:'rgb(100, 0, 255)',
            //   0.9:'rgb(100, 0, 40)',
            //   1.0:'red'
            // }
          })
          AMap_HeatMap.setDataSet({
            data: heatmapData,
            max: 21
          })
        })
        // MapContainer.add(AMap_HeatMap)
      })
    },

    // 定位弹窗
    pointPopup(e, type) {
      if (type == 'text') {
        this.$refs.test.open(e)
      }
      if (type == 'case') {
        this.$refs.case.open(e.orderNum)
      }
      if (type == 'laojiu') {
        this.$refs.laojiu.open(e)
      }
      if (type == 'ment') {
        this.$refs.mentou.open(e.id)
      }
      if (type == 'bujianmap') {
        this.$refs.bujianmap.open(e)
      }
    },

    // 刷新页面
    reload() {
      this.isrouterDisplay = false
      this.$nextTick(() => {
        this.isrouterDisplay = true
      })
    }
  }
}
</script>
<style lang="less">
.swiper-container {
  height: 400px;
}

.container {
  width: 100%;
  height: 100%;
}

#container-map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 100;
}

.router-view {
  position: relative;
  top: 100px;
  height: 948px;
}

.amap-logo {
  display: none !important;
  opacity: 0;
}

.amap-copyright {
  opacity: 0;
  display: none !important;
}

.button {
  width: 100px;
  height: 20px;
  background: #fff;
  position: absolute;
  z-index: 10000;
}

.icon-shili {
  position: absolute;
  z-index: 1001;
  right: 580px;
  bottom: 100px;

  p {
    display: flex;
    align-items: center;
    margin-top: 10px;

    span {
      display: inline-block;
    }

    span:nth-child(1) {
      width: 18px;
      height: 10px;
      margin-right: 10px;
    }

    span:nth-child(2) {
      font-size: 14px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #ffffff;
    }

    img {
      // width: 18px;
      height: 22px;
      margin-right: 8px;
    }
  }
}

.home-dianewi {
  bottom: 360px;
}
</style>
